<?php
class Zendvn_System_Auth{
	protected $_messageError = null;
	
	public function login($arrParam,$option = null){
		//1. Khoi tao ZendDb
		$db = Zend_Registry::get('connectDb');
		//2. Khoi tao Zend_Auth
		$auth = Zend_Auth::getInstance();
		//3. Khoi tao Zend_Auth_Adapter_DbTable
		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
		//4. + Ket noi toi bang chua DL tai khoan
		//   + Dieu kien them neu cam
		$authAdapter->setTableName('users')
					->setIdentityColumn('user_name')
					->setCredentialColumn('password');
		$select = $authAdapter->getDbSelect();
		$select->where('status = 1');
		
		//5 Dua du lieu tu form dang nhap vao va so sanh
		$encode = new Zendvn_Encode();
		if(!empty($arrParam['user_name'])){
			$user_name = $arrParam['user_name'];
		}
		if(!empty($arrParam['password'])){
			$password  = $encode->encode($arrParam['password']);
		}
		$authAdapter->setIdentity($user_name);
		$authAdapter->setCredential($password);

		//6. Lay ket qua truy van cua Zend_Auth	sau khi so sanh		
		$result = $auth->authenticate($authAdapter);
		
		$flag = false;
		if(!$result->isValid()){
				//$error = $result->getMessages();
				//$this->_messageError = current($error);
				$this->_messageError = 'Tài khoản hoặc mật khẩu không đúng !';
		}else{			
			$omitColumns = array('password');
			$data = $authAdapter->getResultRowObject(null,$omitColumns);	
			$auth->getStorage()->write($data);	
			$flag = true;
		}
		
		return $flag;
	}
	
	public function getError(){
		return $this->_messageError;
	}
	
	public function logout($arrParam = null,$options = null){
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
	}
}